package com.wang.example.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 传统bio 线程池
 */
public class BIOThreadPoolServer {
	public static void main(String[] args) throws IOException {
		ExecutorService executorService
				= Executors.newFixedThreadPool(100);
		ServerSocket serverSocket = new ServerSocket(9000);
		System.out.println("端口绑定成功");
		while(true){
			// 获取socket套接字 accept()阻塞点
			Socket socket = serverSocket.accept();
			System.out.println("有新客户端连接上来了...");
			//开启一个线程，处理该socket的数据接收和发送
			executorService.submit(()->{
				try (
						//输入流
						InputStream is = socket.getInputStream();
						//输出流
						OutputStream out =socket.getOutputStream()
				) {
					byte[] b = new byte[1024];
					while (true) {//循环读取数据
						//read()阻塞点，只有等到数据准备好，才会往下执行
						int data = is.read(b);
						if (data != -1) {
							String info = new String(b, 0, data, "UTF-8");
							System.out.println("收到消息：" + info);
							//阻塞方法，收到了消息
							out.write(new String(info + " 世界").getBytes("UTF-8"));
						} else {
							break;
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (socket != null) {
						try {
							socket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			});
		}
	}
}
